﻿using System.Linq;
using System.Modules.ExceptionHanlding;
using System.Reflection;

namespace System.Modules.Contracts.DTO
{
    /// <summary>
    /// Initiator | Initiate all properties
    /// </summary>
    [Serializable]
    public class Initiator
    {
        /// <summary>
        /// Initiator | Initiate all properties
        /// </summary>
        public Initiator()
        {
            try
            {
                var properties = GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static).ToList();
                var count = properties.Count;
                for (var i = 0; i < count; i++)
                {
                    var property = properties[i];
                    if (property.GetIndexParameters().Length > 0) continue;
                    if (!property.CanRead) continue;
                    if (!property.CanWrite) continue;
                    if (!property.PropertyType.IsClass) continue;
                    if (property.PropertyType.GetConstructor(Type.EmptyTypes) == null) continue;
                    if (property.GetValue(this, null) != null) continue;
                    property.SetValue(this, Activator.CreateInstance(property.PropertyType), null);
                }
            }
            catch (Exception exception)
            {
                exception.Handle();
            }
        }
    }
}
